﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using MultiThumbnail.Converters;

namespace MultiThumbnail
{
    public class ThumbnailGenerator
    {
        private readonly ConverterSettings _converterSettings = new ConverterSettings();
        public ConverterSettings ConverterSettings
        {
            get { return _converterSettings; }
        }

        /// <summary>
        /// True to export each page to each file. Otherwise only first page will be exported.
        /// </summary>
        public static bool ExportAllPages { get; set; }

        /// <summary>
        /// Generate a thumbnail for specified file. Use auto-detecion for file type.
        /// The result file will be auto-generated. It will be fileName + ".thumb" + Path.GetExtension(fileName);
        /// </summary>
        /// <param name="fileName">The file path to convert from.</param>
        /// <returns></returns>
        public bool GenerateFor(string fileName)
        {
            return GenerateFor(fileName, fileName + ".thumb." + _converterSettings.ImageFormat.ToString().ToUpper(CultureInfo.InvariantCulture), Path.GetExtension(fileName));
        }

        /// <summary>
        /// Generate a thumbnail for specified file.
        /// </summary>
        /// <param name="path">The file path to convert from.</param>
        /// <param name="resultPath">The result file path for save file to.</param>
        /// <returns></returns>
        public bool GenerateFor(string path, string resultPath)
        {
            return GenerateFor(path, resultPath, null);
        }

        /// <summary>
        /// Generate a thumbnail for specified file.
        /// </summary>
        /// <param name="path">The file path to convert from.</param>
        /// <param name="extension">The file extension (in some cases, it can be not same as in a file).</param>
        /// <param name="resultPath">The result file path for save file to.</param>
        /// <returns></returns>
        public bool GenerateFor(string path, string resultPath, string extension)
        {
            if (path == null) throw new ArgumentNullException("path");
            if (extension == null)
                extension = Path.GetExtension(path);
            if (string.IsNullOrEmpty(extension))
                throw new ArgumentException("The extension can't be null or empty.");
            extension = extension.TrimStart('.').ToUpperInvariant();
            var converter = ThumbnailFactory.FindConverterFor(extension);
            if (converter == null)
                return false;
            converter.ConverterSettings = ConverterSettings;
            ConverterSettings.CurrentExtension = extension;
            try
            {
               // _result = false;
				//Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
				//var t = new Thread(StartConverter);
				//t.SetApartmentState(ApartmentState.STA);
				//t.Start(new StartConverterParams{Converter = converter, Path = path, ResultPath = resultPath});
				//t.Join();
                //return _result; 
				return converter.CreateMiniature(path, resultPath);  
            }
            catch (ConverterException)
            {
                return false;
            }
        }

        //private bool _result;

        //private void StartConverter(object value)
        //{
        //    var pars = (StartConverterParams)value;
        //    _result = pars.Converter.CreateMiniature(pars.Path, pars.ResultPath);            
        //}

        public bool IsValidExtension(string fileName)
        {
            if (fileName == null) throw new ArgumentNullException("fileName");
            var ext = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(ext))
                return false;
            var extension = ext.TrimStart('.').ToUpper(CultureInfo.InvariantCulture);
            return AllAllowedExtensions.Any(e => e == extension);
        }

        public static IEnumerable<string> AllAllowedExtensions
        {
            get
            {
                var allExtensions = new List<string>();
                var types = typeof (ThumbConverter).Assembly.GetTypes().Where(t => t.BaseType == typeof (ThumbConverter));
                foreach (
                    var attribute in
                        types.Select(
                            type => type.GetCustomAttributes(typeof (ExtensionAttribute), true).OfType<ExtensionAttribute>()).
                            SelectMany(extAttrs => extAttrs))
                {
                    allExtensions.AddRange(attribute.Extensions);
                }
                return allExtensions.ToArray();
            }
        }
    }
}
